
import { ReactiveComponent, SingleReactiveComponent } from "@/models/reactiveComponent";
import { computed } from "vue";
import { TDatasetServices } from "@/services/datasetServices";
import { TSqlAnalyzeService } from "@/services/sqlAnalyzeServices";
import { TDbServices } from "@/services/dbServices";
import { TUtilsService } from "@/services/utilsServices";


export type TReactdataServices = ReturnType<typeof getServices>

export function getServices(services: {
    dataset: TDatasetServices,
    sqlAnalyze: TSqlAnalyzeService,
    db: TDbServices,
    utils: TUtilsService
}) {

    function getFilterUtils(model: SingleReactiveComponent,) {
        const table = services.sqlAnalyze.getTableNames(model.sqlInfo.sql)[0]

        const sqlQuery = services.utils.createSqlQuery(model.id, model.sqlInfo.sql)
        const handler = getFilterHandler(model)

        function getData() {
            return computed(() => sqlQuery.query())
        }

        function removeFilter() {
            services.dataset.removeFilters(model.id, table)
            handler.removeFilter()
        }

        return {
            getData,
            addFilter: handler.addFilter,
            addFilterWithExprFn: handler.addFilterWithExprFn,
            removeFilter,
        }
    }


    function getFilterHandler(model: ReactiveComponent) {
        function removeFilter() {
            model.updateInfos.forEach(info => {
                services.dataset.removeFilters(model.id, info.table)
            })
        }

        function addFilter(expr: string) {
            model.updateInfos.forEach(info => {
                services.dataset.addFilter(model.id, info.table, `${info.field} ${expr}`)
            })

        }

        function addFilterWithExprFn(exprFn: (field: string) => string) {
            model.updateInfos.forEach(info => {
                services.dataset.addFilter(model.id, info.table, exprFn(info.field))
            })

        }

        return {
            removeFilter,
            addFilter,
            addFilterWithExprFn
        }
    }

    return {
        getFilterUtils,
        getFilterHandler,
    }
}











